require 'json'
require 'mime/types'
require 'open-uri'

class SearchController < ApplicationController
    @req_time = DateTime.current #initialize the moment when the request was initiated.
    
        def index
        end

        def srch
        
                # actual api calls for search go here...
                @session_id =  request.headers["rack.session"]["session_id"]
                @search_string = params["message"]
                @hash_for_view = {}
				@hash_for_see = {}
                #@master_list = ['adored','afraid','aggravated','agitated','agonized','alarmed','alienated','amazed','amused','angry','anguished','annoyed','antsy','anxious','apprehensive','aroused','ashamed','astonished','attracted','awful','awkward','bashful','bewildered','bitter','blissed','bored','brave','best','better','calm','caring','cautious','cheerful','comfortable','compassionate','concerned','confident','confused','contempt','content','like','good','happy']
                #client = TwitterOAuth::Client.new
                @emo = {'adored'=> 2.5, 'afraid'=> -1.6, 'aggravated'=> -1.9,'agitated' => -2,'agonized' => -2.9,'alienated' => -2.3,'amazed' => 2.5,'amused' => 1.6,'angry' => -3,'anguished' => -1.5,'annoyed' => -1.8,'antsy' => -2.6,'anxious' => 2.7,'apprehensive' => -1.7 ,'ashamed' => -2.2,'astonished' => 2.5 ,'attracted' => 3.5,'awful' => -3.5,'awkward' => -3.2,'bashful' => -2.6,'bewildered' => -1.7,'bitter' => -2,'blissed' => 4,'bored' => -3,'brave' => 2.2,'best' => 2.8, 'better' => 1.8 ,'calm' => 1.4,'caring' => 1.5,'cautious' => -1.5,'cheerful' => 3.6,'comfortable' => 2.1,'compassionate' => 1.5,'concerned' => 1.6,'confident' => 3.2,'confused' => -2.0,'contempt' => -3, 'like' => 2, 'good' => 3, 'happy' => 2.5 }
                
                @master_list = @emo.keys
               
			   t = Thread.new { @tw_result = self.twt_search(params["message"]) }
                
                f = Thread.new { @fb_result = self.fb_search(params["message"]) }
                
                t.join
                f.join

                render "chsrch"

        end
        
        def twt_search(q, options={})
               options[:page] ||= 1
                options[:rpp] ||= 2000
                options[:q] = URI.escape(q)
                args = options.map{|k,v| "#{k}=#{v}"}.join('&')
                response = open("http://search.twitter.com/search.json?lang=en#{args}", 'User-Agent' => 'raghav')
                @tw_result = JSON.parse(response.read)

                @hash_for_view = tw_processing(@master_list, @tw_result["results"])
               
        end
        
        def fb_search(srch)
                str  = URI.escape(srch)
                response = open('http://graph.facebook.com/search?q=' + str  + '&type=post' + '&limit=200' , 'User-Agent' => 'puneet')
                @result=JSON.parse(response.read)
                
                @hash_for_see = fb_processing(@master_list,@result["data"])
        end   
                
        
        def tw_processing(master_list, messages)

                hash_for_view ={}
                
                #puts '=================================' + messages.length.to_s
                
                messages.length.times do |i|

                        #msgwords = messages[i]["text"].split(/ /)
                        #puts '=======words from the message ======================'
                        #puts msgwords

                        score = get_score(messages[i]["text"])

                        hash_for_view[messages[i]["text"]] = score.to_f
                       # db_insert(messages[i]["text"], score, "Twitter",messages[i]["iso_language_cd"])
                end

                return hash_for_view
        end # of function tw_processing

        def fb_processing(master_list, messages)

                #@result["data"].each do |elem| %>
                
                #puts '===============' + messages.length.to_s + '==============================================='
                #puts messages.inspect

               hash_for_see ={}
                
                messages.length.times do |i|

                        #msgwords = messages[i]["text"].split(/ /)
                        #puts '=======words from the message ======================'
                        #puts msgwords

                        
                        if not messages[i]["message"].nil?
                                #puts  '========================' + 'launching scoring for ' + messages[i]["message"]
                                score = get_score(messages[i]["message"])
                                hash_for_see[messages[i]["message"]] = score.to_f                                
                        end

                        
               #         db_insert(messages[i]["message"], score,'Facebook','en')
                end

                return hash_for_see
        end # of function calc_score


        def get_score (msg)
                #mw = @emo
                score = 0
                #puts '========== message received for scoring  ==================='      
                #puts msg

                #puts '========== master list  ==================='
                #puts @master_list
                                
                msgwords = msg.split(/ /)
                score_words = msgwords & @master_list # array & will leave only scorable words
                #puts '==========score words ==================='
                #puts score_words

                if not score_words.nil? 
                        score_words.each do |w|
                        x=0
                                #puts 'word =>' +  w
                            #v = @emo.select {|key, value| key = w}
                            #puts "dumping @emo[w] now"
                            #@emo[w].inspect
                            x = @emo[w]
							#value.each do |key,value|
							#puts "w = " + w
							#puts v.inspect
							#x = v[w]
							#end
                                #puts 'score for ' + w + ' is ' +  x.to_s
                                #puts 'scoring for ' + w + ' = ' + x
                                score = score.to_f + x.to_f
                        end
                end
                puts "score for the message "+msg
                puts score
                return score
        end


       #def db_insert(textvalue, score, site_name, lang_cd)

               # msg = Msgdata.new
                
                #(msg_arry["created_at"])

                #msg.profile_image =  msg_arry["profile_image_url"]
                #msg.from_user_id = msg_arry["from_user_id_str"]
                #msg.id_str = msg_arry["id_str"]
                #msg.from_user =  msg_arry["from_user"]
               # msg.message =  textvalue # msg_arry["text"]
                #msg.metadata =  msg_arry["metadataresult_type"]
                #msg.id =  msg_arry["id"]
              #  msg.language_cd =  lang_cd # msg_arry["iso_language_cd"]
                #msg.source_url =  msg_arry["source"]
              #  msg.score= score
               # msg.request_time = @req_time
              #  msg.session_id =  request.headers["rack.session"]["session_id"]
              #  msg.search_string = params["message"]
                #session.session_id
              #  msg.site_name = site_name
                
              #  msg.save

     #   end # end of db_insert

       
        
        

            
        

end  # end of class

